from xadmin.models import Sites, GroupPermission

def isAdmin(func):
    def inner(request, *args, **kwargs):
        if request.path.startswith('/admin/') and '/login/' not in request.path:
            return func(request, *args, **kwargs)
        else:
            return {}
    return inner


@isAdmin
def site_list(request):
    sites = Sites.objects.all()

    siteid = request.GET.get('siteid', '1')
    site = Sites.objects.filter(id=siteid).first()
    return {
        'sites': sites,
        'site': site,
        'siteid': siteid
    }


@isAdmin
def perm_list(request):
    user = request.user
    siteid = request.GET.get('siteid', '1')
    if user.is_authenticated:
        groups = user.user_group.all()
        if groups:
            has_permission = GroupPermission.objects.filter(site_id=siteid, group__in=groups)
            permission_json = {}
            if has_permission:
                for perm in has_permission:
                    if perm.permission_type in permission_json:
                        if perm.permission_slug in permission_json[perm.permission_type]:
                            pass
                        else:
                            permission_json[perm.permission_type].append(perm.permission_slug)
                    else:
                        permission_json[perm.permission_type] = [perm.permission_slug]

                return {
                    'perm_dic': permission_json
                }

    return {
        'perm_dic': {}
    }
